package md.frolov.bible.model;

import java.io.File;
import java.util.regex.Matcher;

import md.frolov.bible.Constants;

public class Verse {
	private final String contents;
	private final String localId;
	private final String id;
	private final Chapter chapter;
	
	public Verse(String id, String localId, String contents, Chapter chapter, File file){
		this(id, localId, contents, chapter, Archive.getInstance().getModuleByFile(file));
	}
	
	public Verse(String id, String localId, String contents, Chapter chapter){
		this(id, localId, contents, chapter, (Module)null);
	}
	
	public Verse(String id, String localId, String contents, Chapter chapter, Module module){
		this.contents = contents;
		this.localId = localId;
		this.id = id;
		if(chapter == null){
			int ix = id.indexOf('-');
			String a = id.substring(0,ix);
			String b = id.substring(ix+1);
			Matcher m1 = Constants.idPattern.matcher(a);
			Matcher m2 = Constants.idPattern.matcher(b);
			Book book;
			if(m1.matches() && m2.matches()){
					book = module.getBookById(m1.group(1));
					chapter = book.getChapterById(m1.group(1)+"."+m1.group(2));
			} else throw new IllegalArgumentException();
		}
		
		this.chapter = chapter;
	}

	public String getContents() {
		return contents;
	}

	public String getLocalId() {
		return localId;
	}

	public String getId() {
		return id;
	}	
	
	public Chapter getChapter(){
		return chapter;
	}
	
	public String getUrl(){
		if(id.contains("-")){
			int ix = id.indexOf('-');
			String a = id.substring(0,ix);
			String b = id.substring(ix+1);
			Matcher m1 = Constants.idPattern.matcher(a);
			Matcher m2 = Constants.idPattern.matcher(b);
			if(m1.matches() && m2.matches()){
				if(m1.group(1).equals(m2.group(1)) && m1.group(2).equals(m2.group(2)))
					return chapter.getBook().getModule().getUrl() + m1.group(1)+"."+m1.group(2)+"."+m1.group(3)+"-"+m2.group(3);
			}
			return chapter.getBook().getModule().getUrl() + id.substring(0,ix-1);
		}
		return chapter.getBook().getModule().getUrl() + id;
	}

	public String getName(){
		if(id.contains("-")){
			int ix = id.indexOf('-');
			String a = id.substring(0,ix);
			String b = id.substring(ix+1);
			Matcher m1 = Constants.idPattern.matcher(a);
			Matcher m2 = Constants.idPattern.matcher(b);
			if(m1.matches() && m2.matches()){
				if(m1.group(1).equals(m2.group(1)) && m1.group(2).equals(m2.group(2)))
					return chapter.getBook().getName()+" "+chapter.getLocalId()+":"+m1.group(3)+"-"+m2.group(3);
			}
			return chapter.getBook().getName()+" "+chapter.getLocalId()+":"+m1.group(3)+"-...";
		}
		return chapter.getBook().getName()+" "+chapter.getLocalId()+":"+getLocalId();
	}
}
